package com.xmg.p2p.base.controller;

import com.xmg.p2p.base.domain.SystemDictionaryItem;
import com.xmg.p2p.base.domain.UserFile;
import com.xmg.p2p.base.service.ISystemDictionaryItemService;
import com.xmg.p2p.base.service.IUserFileService;
import com.xmg.p2p.base.util.JSONResult;
import com.xmg.p2p.base.util.UploadUtil;
import com.xmg.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * lcd  2020/5/20
 * Description:
 */
@Controller
public class UserFileController {
    @Autowired
    private IUserFileService userFileService;
    @Autowired
    private ServletContext servletContext;
    @Autowired
    private ISystemDictionaryItemService systemDictionaryItemService;

    @RequestMapping("userFile")
    public String userFile(Model model, HttpServletRequest request){
        List<UserFile> userFiles=userFileService.query(UserContext.getLogininfo().getId(),false);
        if (userFiles.size() > 0) {
            model.addAttribute("userFiles",userFiles);
            List<SystemDictionaryItem> fileTypes = systemDictionaryItemService.queryBySn("userFileType");
            model.addAttribute("fileTypes",fileTypes);
            return "userFiles_commit";
        }else {
            model.addAttribute("sessionid", request.getSession().getId());
            userFiles=userFileService.query(UserContext.getLogininfo().getId(),true);
            model.addAttribute("userFiles",userFiles);
            return "userFiles";
        }


    }

    /**
     * 单个的上传文件
     **/
    @RequestMapping("userFileUpload")
    @ResponseBody
    public void userFileUpload(MultipartFile file) {
        String basePath = servletContext.getRealPath("/upload");
        String fileName = UploadUtil.upload(file, basePath);
        fileName= "/upload/" + fileName;
        userFileService.apply(fileName);

    }

    @RequestMapping("userFile_selectType")
    @ResponseBody
    public JSONResult selectType(long[] fileType,long[] id){
        if(fileType!=null && id!=null && fileType.length==id.length){
            userFileService.updateType(fileType, id);
        }
        return new JSONResult();
    }
}
